package com.example.sprintboot.controller;

import com.example.sprintboot.common.Result;
import com.example.sprintboot.service.ApiService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * API调用测试控制器
 * 演示如何调用外部API
 */
@RestController
@RequestMapping("/api-test")
public class ApiTestController {

    @Resource
    private ApiService apiService;

    /**
     * 示例1：调用GET请求
     * 测试URL：http://localhost:9090/api-test/get?url=https://api.example.com/data
     */
    @GetMapping("/get")
    public Result testGet(@RequestParam String url) {
        String response = apiService.callGetApi(url);
        return Result.success(response);
    }

    /**
     * 示例2：调用带参数的GET请求
     */
    @GetMapping("/get-with-params")
    public Result testGetWithParams(
            @RequestParam String baseUrl,
            @RequestParam String param1,
            @RequestParam String param2) {
        String response = apiService.callGetApiWithParams(baseUrl, param1, param2);
        return Result.success(response);
    }

    /**
     * 示例3：调用POST请求
     */
    @PostMapping("/post")
    public Result testPost(@RequestParam String url, @RequestBody Map<String, Object> data) {
        String response = apiService.callPostApi(url, data);
        return Result.success(response);
    }

    /**
     * 示例4：调用带Token的API
     */
    @GetMapping("/get-with-auth")
    public Result testGetWithAuth(@RequestParam String url, @RequestParam String token) {
        String response = apiService.callApiWithAuth(url, token);
        return Result.success(response);
    }

    /**
     * 示例5：调用本地API（调用自己项目的接口）
     */
    @GetMapping("/call-local")
    public Result testCallLocal(@RequestParam String localUrl) {
        String response = apiService.callLocalApi(localUrl);
        return Result.success(response);
    }

    /**
     * 示例6：实际应用场景 - 调用天气API
     * 这里使用一个公开的天气API作为示例
     */
    @GetMapping("/weather")
    public Result getWeather(@RequestParam String city) {
        try {
            // 示例：调用天气API（这里只是示例，实际需要替换为真实的API）
            String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=YOUR_API_KEY";
            // 注意：实际使用时需要替换为真实的API Key
            
            // 这里演示调用本地API作为替代
            String localUrl = "http://localhost:9090/article/selectAll";
            String response = apiService.callGetApi(localUrl);
            
            return Result.success("这是示例，实际应该调用天气API。本地API响应：" + response);
        } catch (Exception e) {
            return Result.error("获取天气失败: " + e.getMessage());
        }
    }
}

